package com.hospes.rmes.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hospes.rmes.App;
import com.hospes.rmes.R;
import com.hospes.rmes.core.ImageDescriptor;
import com.hospes.rmes.models.News;
import com.hospes.rmes.utils.Utils;

import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Andrew Khloponin
 * Date: 17.06.11
 */
public class NewsAdapter extends ArrayAdapter<News> {
	private ArrayList<News> newses;
	private Context context;

	public NewsAdapter(Context context, int textViewResourceId, ArrayList<News> newses) {
		super(context, textViewResourceId, newses);
		this.newses = newses;
		this.context = context;
	}

	static class ViewHolder {
		TextView tvTitle, tvText;
		ImageView ivPoster;
		ProgressBar pbPoster;
	}

	@Override
	public View getView(int i, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			LayoutInflater _inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = _inflater.inflate(R.layout.list_item_news, null);
			holder = new ViewHolder();
			holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_item_news_title);
			holder.tvText = (TextView) convertView.findViewById(R.id.tv_item_news_text);
			holder.ivPoster = (ImageView) convertView.findViewById(R.id.iv_item_news_poster);
			holder.pbPoster = (ProgressBar) convertView.findViewById(R.id.pb_item_news_poster);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final News news = newses.get(i);
		if (news != null) {
			holder.tvTitle.setText(news.title);
			holder.tvText.setText(Utils.FromDateToString(news.date));
			ImageDescriptor image = new ImageDescriptor(Utils.getFileName("http://rmes.com.ua/files/images/" + news.files), "http://rmes.com.ua/files/images/" + news.files);
			App.imageDownloader.download(image, holder.ivPoster, holder.pbPoster);
		}

		return convertView;
	}

	public int getCount() {
		return newses.size();
	}

	public News getItem(int i) {
		return newses.get(i);
	}

	public long getItemId(int i) {
		return 0;
	}

	public void setList(ArrayList<News> newses) {
		this.newses = newses;
	}
}
